package com.xuhuan.practice.controller;

import com.xuhuan.practice.dto.article.ArticleInfoDTO;
import com.xuhuan.practice.dto.page.PageResult;
import com.xuhuan.practice.validator.group.AddGroup;
import com.xuhuan.practice.validator.group.UpdateGroup;
import com.xuhuan.practice.entity.Article;
import com.xuhuan.practice.response.Result;
import com.xuhuan.practice.service.ArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: huan.xu
 * @create: 2024/6/11 21:57
 * @description: 文章管理
 **/
@RequestMapping("/article")
@RestController
public class ArticleController {

  @Autowired
  private ArticleService articleService;

  /**
   * 文章新增
   *
   * @param articleInfoDTO
   * @return
   */
  @PostMapping
  public Result add(@RequestBody @Validated(AddGroup.class) ArticleInfoDTO articleInfoDTO) {
    articleService.add(articleInfoDTO);
    return Result.success();
  }

  /**
   * 文章列表分页查询
   *
   * @return
   */
  @GetMapping
  public Result<PageResult<ArticleInfoDTO>> list(
      Integer pageNum,
      Integer pageSize,
      @RequestParam(required = false) Integer categoryId,
      @RequestParam(required = false) String state
  ) {
    PageResult<ArticleInfoDTO> dataList = articleService.list(pageNum, pageSize, categoryId, state);
    return Result.success(dataList);
  }

  /**
   * 获取文章详情
   *
   * @return
   */
  @GetMapping("/detail")
  public Result<ArticleInfoDTO> detail(Integer articleId) {
    Article article = articleService.getById(articleId);
    ArticleInfoDTO articleInfoDTO = new ArticleInfoDTO();
    BeanUtils.copyProperties(article, articleInfoDTO);
    return Result.success(articleInfoDTO);
  }

  /**
   * 删除文章
   *
   * @param articleId
   * @return
   */
  @DeleteMapping
  public Result delete(Integer articleId) {
    Article article = articleService.getById(articleId);
    if (article == null) {
      return Result.error("文章ID不正确");
    }
    articleService.deleteById(articleId);
    return Result.success();
  }

  /**
   * 更新文章
   *
   * @param articleInfoDTO
   * @return
   */
  @PutMapping
  public Result update(@RequestBody @Validated(UpdateGroup.class) ArticleInfoDTO articleInfoDTO) {
    Article article = articleService.getById(articleInfoDTO.getId());
    if (article == null) {
      return Result.error("文章信息获取失败");
    }
    articleService.update(article);
    return Result.success();
  }
}

